package com.yan.util;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;

public class CastMapper {

    /**
     * 对象转化类，
     * 将o对象与cl类表述类字段相同的字段赋值并创建对象返回
     * @param o 入参对象
     * @param cl 目标类信息
     * @return 目标对象
     */
    public static Object CastTo(Class<?> cl,Object o){
        try {
            Object target = cl.newInstance();
            Field[] fields = cl.getDeclaredFields();
            AccessibleObject.setAccessible(fields,true);
            HashMap<String,Object> fieldMap = new HashMap<>();
            Class<?> ocl = o.getClass();
            Field[] oField = ocl.getDeclaredFields();
            AccessibleObject.setAccessible(oField,true);
            for(Field field:oField){
                fieldMap.put(field.getName(),field.get(o));
            }
            for(Field targetField:fields){
                if(fieldMap.containsKey(targetField.getName())){
                    if(!Modifier.isFinal(targetField.getModifiers()))
                        targetField.set(target,fieldMap.get(targetField.getName()));
                }
            }
            return target;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
